#  injector.rb
#
#  This file is part of myvnet.
#
#  Copyright (C) 2008  Filipe David Borba Manana,  fdmanana@gmail.com
#
#  myvnet is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  myvnet is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with myvnet.  If not, see <http://www.gnu.org/licenses/>.
 

require 'thread'
require 'lib/protocols/ethernet'
require 'lib/packet/raw_socket'
require 'lib/exceptions'


module Packet
  
  # Injects packets into the network.
  # 
  # Client code invokes the instance method add_packet, which
  # adds a packet to an internal queue that is accessed in a
  # FCFS (First Come First Served) fashion. Worker threads of
  # this class will then retrieve the packets from the queue
  # and inject them into the network.
  #
  class Injector
    
    # === Synopsis
    #
    #   Packet::Injector.new(interface)
    #
    # === Args
    #
    # +interface+::
    #   Name of the network interface to use for packet injection.
    #
    # === Exceptions
    #
    # +RawSocketError+::
    #   If by some reason it was not possible to create a Linux Raw Socket
    #   for packet injection.
    #
    # === Description
    #
    # Instantiates a packet injector.
    #    
    def initialize(interface)
      @iface = interface
      @socket = Packet::RawSocket.new @iface
      @packet_queue = []
      @queue_mutex = Mutex.new
      @empty_queue = ConditionVariable.new
      @worker_threads = ThreadGroup.new
      
      # Create worker threads.
      # They fetch packets from the queue and inject them
      # into the network.
      #
      Thread.abort_on_exception = true
      1.upto(3) do |i|
        
        t = Thread.new(i) { |id|
          Thread.current[:id] = id
          
          while true do
            packet = get_packet
            inject_packet(packet)            
          end
        }
        
        @worker_threads.add t
      end
      
    end
    
    
    # === Synopsis
    # 
    #   Packet::Injector#add_packet(packet, daemon_name)
    #   
    # === Args
    # 
    # +packet+::
    #   A layer 2 packet, of the TCP/IP protocol suite, to inject into
    #   the network. At the moment only Ethernet is supported as a
    #   layer 2 protocol. By other words, it must be an instance of
    #   Ethernet::Packet.
    #   
    # +daemon_name+::
    #   Name of the daemon who invoked this method. Used for debugging
    #   and logging.
    # 
    # === Return
    # 
    # No value.
    # 
    # === Description
    # 
    # Adds a packet, built by a daemon, into the outgoing packets queue.
    # The packet will then be injected to the network as soon as possible.
    #
    def add_packet(packet, daemon_name)
      @queue_mutex.synchronize do
        @packet_queue.push packet                
        @empty_queue.signal                
      end
      
      if $log[:packet].debug?
        msg = "Packet added to outgoing queue "
        msg << "by daemon `#{daemon_name}':\n"
        msg << packet.to_s
        $log[:packet].debug msg
      end      
    end
    
    
    def shutdown
      @socket.close
    end
    
            
    private
    
    def get_packet
      packet = nil
      
      @queue_mutex.synchronize do
        @empty_queue.wait(@queue_mutex) while @packet_queue.empty?
        packet = @packet_queue.shift        
      end
      
      if $log[:packet].debug?
        thread_id = Thread.current[:id]
        msg = "Packet taken from outgoing queue"
        msg << " by thread `#{thread_id}':\n"
        msg << packet.to_s
        $log[:packet].debug msg
      end      
            
      packet      
    end
    
            
    def inject_packet(packet)
      thread_id = Thread.current[:id]
      
      unless packet.instance_of? Ethernet::Packet
        msg = "Thread `#{thread_id}', invalid packet type to inject:"
        msg << " `#{packet.class.name}'"
        $log[:packet].error msg
        return
      end
      
      bytes = packet.to_bstream
      sent = @socket.send bytes
      
      if sent == bytes.length
        msg = "Thread `#{thread_id}' injected packet:\n"
        msg << packet.to_s
        $log[:packet].info msg
      else
        msg = "RawSocket sent #{sent} bytes out of #{bytes.length}.\n"
        $log[:packet].error msg
      end
    end    
    
  end  
  
end
